﻿
//雷达图
export const buildChart = function (myChart, data, columnFields, rowFields, options) {
  //一级维度
  var dimensionField = columnFields.find(function (d) {
    return d.slaveType === 0;
  });
  //度量
  var measureField = rowFields.find(function (d) {
    return d.slaveType === 1;
  });
  if (!dimensionField) {
    dimensionField = rowFields.find(function (d) {
      return d.slaveType === 0;
    });
    measureField = columnFields.find(function (d) {
      return d.slaveType === 1;
    });
  }
  if (!dimensionField || !measureField) {
    return false;
  }
  //二级维度
  var subdimensionField;
  if (options.colorMark && options.colorMark.annexField) {
    subdimensionField = options.colorMark.annexField;
  }

  //按一级维度排序
  data = Enumerable.from(data).orderByDescending(function (d) {
    return d[dimensionField.name];
  }).toArray();

  var config = options.chartConfig;

  //提取一级维度
  var categories = Enumerable.from(data).select(function (d) {
    return d[dimensionField.name];
  }).distinct().toArray();
  var groups = [];
  if (subdimensionField) {
    //按二级维度分组
    var groups = Enumerable.from(data).groupBy(function (d) {
      return d[subdimensionField.name];
    }).toArray();
    if (subdimensionField.dataType == 4) {
      groups = Enumerable.from(groups).orderBy(function (d) {
        return d.key();
      }).toArray();
    }
  }
  //轴文字样式
  var axis_nameTextStyle = {
    color: config.axisStyle.fontColor,
    fontSize: config.axisStyle.fontSize,
    fontFamily: config.axisStyle.fontFamily
  }
  //数据条标签配置
  var labelOption = {
    normal: {
      show: config.textStyle["display"] !== "none",
      distance: 5,
      align: "left",
      verticalAlign: "middle",
      fontSize: config.textStyle["font-size"],
      fontFamily: config.textStyle["font-family"],
      color: config.textStyle["fill"]
    }
  };
  var serieRadar = {
    type: 'radar',
    label: labelOption,
    data: []
  }
  var option_chart = {
    color: config.MultiColors,
    legend: {
      data: [],
      textStyle: axis_nameTextStyle,
      show: config.showLegend == undefined ? true : config.showLegend,
      type: 'scroll',
      pageIconColor: config.axisStyle.fontColor,
      pageTextStyle: axis_nameTextStyle,
      itemWidth: 14,
      itemHeight: 14
    },
    toolbox: {
      show: true,
      orient: 'vertical',
      top: 'center',
      right: 20,
      feature: {
        mark: {show: true},
        saveAsImage: {show: true}
      },
      iconStyle: {
        borderColor: config.axisStyle.fontColor,
        textPosition: "left"
      }
    },
    radar: {
      name: {
        textStyle: axis_nameTextStyle
      },
      shape: "circle",
      indicator: [
        //{ name: '销售（sales）', max: 6500 },
        //{ name: '管理（Administration）', max: 16000 },
        //{ name: '信息技术（Information Techology）', max: 30000 },
        //{ name: '客服（Customer Support）', max: 38000 },
        //{ name: '研发（Development）', max: 52000 },
        //{ name: '市场（Marketing）', max: 25000 }
      ],
      silent: true
    },
    calculable: true,
    grid: [{
      top: 30,
      bottom: 15,
      left: 5,
      right: 40,
      containLabel: true
    }],
    series: [serieRadar],
    others: {
      dimensionField: dimensionField,
      measureField: measureField,
      subdimensionField: subdimensionField,
      categories: categories,
      datamarking: options.DataMarking
    }
  }
  categories.forEach(function (c) {
    var max = Enumerable.from(data).where(function (d) {
      return d[dimensionField.name] == c;
    }).max(function (d) {
      return d[measureField.name];
    });
    option_chart.radar.indicator.push({
      name: c,
      max: Math.ceil(max * 1.2)
    });
  });
  if (subdimensionField) {
    groups.forEach(function (group) {
      var legend = group.key();
      option_chart.legend.data.push(legend);
      var source = group.getSource();
      var values = [];
      categories.forEach(function (c) {
        var find = source.find(function (d) {
          return d[dimensionField.name] === c;
        });
        if (find) {
          values.push(find[measureField.name]);
        } else {
          values.push(null);
        }
      });
      serieRadar.data.push({
        name: legend,
        value: values
      });
    });
  } else {
    serieRadar.data.push({
      value: data.map(function (d) {
        return d[measureField.name];
      })
    });
  }
  if (config.fillArea == 1) {
    serieRadar.areaStyle = {}
  }
  config.legendPosition = config.legendPosition || "top";
  if (config.legendPosition == "left") {
    option_chart.legend.orient = "vertical";
    option_chart.legend.x = "left";
  } else if (config.legendPosition == "leftBottom") {
    option_chart.legend.orient = "vertical";
    option_chart.legend.x = "left";
    option_chart.legend.y = "bottom";
  } else if (config.legendPosition == "right") {
    option_chart.legend.orient = "vertical";
    option_chart.legend.x = "right";
    option_chart.toolbox.left = 20;
  } else if (config.legendPosition == "rightBottom") {
    option_chart.legend.orient = "vertical";
    option_chart.legend.x = "right";
    option_chart.legend.y = "bottom";
    option_chart.toolbox.left = 20;
  } else if (config.legendPosition == "bottom") {
    option_chart.legend.y = "bottom";
  }
  return new chart(myChart, option_chart);
}

const chart = function (myChart, opt) {
  var datamarkingopt = opt.others.datamarking;
  var datamarkingmapping = {}
  delete opt.others.datamarking;
  //处理数据脱敏
  if (datamarkingopt) {
    datamarkingopt.dimensions.forEach(function (dko) {
      if (dko.DataMarkingEnable) {
        datamarkingmapping[dko.name] = true;
      }
    });
  }
  var self = this;

  var chart_opt = {
    tooltip: {
      formatter: function (args) {
        /*args[0]
         $vars: (3) ["seriesName", "name", "value"]
        color: "#001EFF"
        componentIndex: 0
        componentSubType: "radar"
        componentType: "series"
        data: {name: "消费者", value: Array(3)}
        dataIndex: 0
        dataType: undefined
        marker: "<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#001EFF;"></span>"
        name: "消费者"
        seriesId: "series00"
        seriesIndex: 0
        seriesName: "series0"
        seriesType: "radar"
        value: (3) [1019, 2951, 1157]
         */
        var tips = "";
        if (opt.others.subdimensionField) {
          tips += args.marker;
          tips += opt.others.subdimensionField.name + ":" + args.name + "<br/>";
        }
        args.value.forEach(function (d, idx) {
          tips += opt.others.categories[idx] + ":" + Number(d).toMeasureFormart(opt.others.measureField.numberFormat) + "<br/>";
        });
        return tips;
      }
    },
    legend: {
      formatter: function (name) {
        var result = name;
        if (datamarkingopt && datamarkingmapping[opt.others.subdimensionField.name]) {
          result = result.marking();
        }
        return result;
      }
    },
    radar: {
      name: {
        formatter: function (value, indicator) {
          var result = value;
          if (datamarkingopt && datamarkingmapping[opt.others.dimensionField.name]) {
            result = result.marking();
          }
          return result;
        }
      }
    }
  }
  var labelFormatter = function (args) {
    var tips = Number(args.value).toMeasureFormart(opt.others.measureField.numberFormat);
    return tips;
  }
  var setOption = function (opt) {
    chart_opt = $.extend(true, chart_opt, opt);
    chart_opt.series.forEach(function (d) {
      d.label.normal.formatter = labelFormatter;
    });
    myChart.setOption(chart_opt);
  }
  //响应点击事件
  myChart.on("click", function (args) {
    if (args.componentType === "series") {
      var calldata = [];
      if (chart_opt.others.subdimensionField) {
        calldata.push({
          field: chart_opt.others.subdimensionField,
          value: [args.name]
        });
      }
      if (self.onselected) {
        self.onselected(calldata);
      }
    }
  });
  if (opt) {
    setOption(opt);
  }
  this.setOption = setOption;

  this.update = function (data) {
    //按一级维度排序
    data = Enumerable.from(data).orderByDescending(function (d) {
      return d[chart_opt.others.dimensionField.name];
    }).toArray();
    //提取一级维度
    var categories = Enumerable.from(data).select(function (d) {
      return d[chart_opt.others.dimensionField.name];
    }).distinct().toArray();
    var groups = [];
    if (chart_opt.others.subdimensionField) {
      //按二级维度分组
      var groups = Enumerable.from(data).groupBy(function (d) {
        return d[chart_opt.others.subdimensionField.name];
      }).toArray();
      if (chart_opt.others.subdimensionField.dataType == 4) {
        groups = Enumerable.from(groups).orderBy(function (d) {
          return d.key();
        }).toArray();
      }
    }
    chart_opt.radar.indicator = [];
    categories.forEach(function (c) {
      var max = Enumerable.from(data).where(function (d) {
        return d[chart_opt.others.dimensionField.name] == c;
      }).max(function (d) {
        return d[chart_opt.others.measureField.name];
      });
      chart_opt.radar.indicator.push({
        name: c,
        max: Math.ceil(max * 1.2)
      });
    });
    chart_opt.legend.data = [];
    var serieRadar = chart_opt.series[0];
    serieRadar.data = [];
    if (chart_opt.others.subdimensionField) {
      groups.forEach(function (group) {
        var legend = group.key();
        chart_opt.legend.data.push(legend);
        var source = group.getSource();
        var values = [];
        categories.forEach(function (c) {
          var find = source.find(function (d) {
            return d[chart_opt.others.dimensionField.name] === c;
          });
          if (find) {
            values.push(find[chart_opt.others.measureField.name]);
          } else {
            values.push(null);
          }
        });
        serieRadar.data.push({
          name: legend,
          value: values
        });
      });
    } else {
      serieRadar.data.push({
        value: data.map(function (d) {
          return d[chart_opt.others.measureField.name];
        })
      });
    }
    chart_opt.others.categories = categories;
    setOption(chart_opt);
  }

}

